#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SLInit(SL *ps)
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
} 

//顺序表的销毁
void SLDestroy(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

//单独看插入的空间够不够
void SLCheckCapacity(SL*ps)
{
	//插入数据之前先看空间够不够
	if (ps->capacity == ps->size)
	{
		//空间已经满了，申请空间
		//增容realloc,要申请多大的空间
		//三目操作符
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		//防止realloc申请失败,给个临时变量
		//ps->arr = (SLDataType*)realloc(ps->arr, newCapacity * 2 * sizeof(SLDataType));
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * 2 * sizeof(SLDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);//直接退出程序，不再继续执行
		}
		//空间申请成功
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}

//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	//第一种解决
	//if (ps == NULL)
	//{
	//	return;
	//}

	//第二种解决
	assert(ps);//等价于assert(ps!=NULL)

	//ps->arr[ps->size] = x;
	//++ps->size;
	SLCheckCapacity(ps);
	ps->arr[ps->size++] = x;//a++,先用后加；++a，先加后用
}

//头插
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	//先让顺序表中已有的数据整体往后挪动一位
	for (int i = ps->size; i>0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];//arr[1]=arr[0]
	}
	ps->arr[0] = x;
	ps->size++;
}

#if 0
void SLPrint(SL s)
{
	for (int i = 0; i < s.size; i++)
	{
		printf("%d ", s.arr[i]);
	}
	printf("\n"); 
}
#endif

//尾删
void SLPopBack(SL* ps)
{
	assert(ps);//不能传空
	assert(ps->size);
	//顺序表不为空
	--ps->size;

}
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);

	//数据整体往前挪动一位
	for (int i = 0; i < ps->size-1 ; i++)
	{
		ps->arr[i] = ps->arr[i + 1];//arr[size-2]=arr[size-1]
	}
	ps->size--;
}


//指定位置之前插入/删除数据
//pos不能是任意的整数
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <=ps->size);
	//在指定位置之前插入数据，空间够不够
	SLCheckCapacity(ps);
	//让pos及之后的数据集体往后挪
	for (int i = ps->size; i>pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];//arr[pos+1]=arr[pos]
	}
	ps->arr[pos] = x;
	ps->size++;
}


//删除指定位置的数据
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i<ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];//arr[size-2]=arr[size-1]
	}
	ps->size--;
}


#if 0
//顺序表的查找
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
		{
			//找到了
			return i;
		}
	}
	//没有找到
	return -1;//无效的下标
}

#endif